package commander;

import fileoperation.FileDeletion;
import gitobject.Branch;
import fileoperation.FileCopy;
import fileoperation.FileStatus;
import fileoperation.FileRead;
import gitobject.Head;
import repository.Repository;

import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
/*
1、git checkout [<branchname>]：切换到名为<branchname>的分支上（更新HEAD指针）
2、git checkout –b [<branchname>]：根据当前分支，创建一个新的名为<branchname>的分支，
并切换到此分支上。如果原来就存在该分支，则将其重置。
3、调用FileStatus函数判断branch 是否存在
4拷贝文件到工作目录，也可用于切换分支
 */
//拷贝文件到工作目录，也可用于切换分支



public class checkout extends Command{
    //切换到名为<branchname>的分支上（更新HEAD指针）
    public void checkout(String branchName) throws Exception{
        if(FileStatus.branchExist(branchName)){
            //新建名为branchName的Head指针
            File HEAD = new File(Repository.getGitDir() + File.separator + this.head);
       //     String currentBranch = FileRead.readBranchFromHead(this.head);
            //读取branchName所指分支
       //     String currentCommit = FileRead.readCommitFromBranch(new File(wrapGit(currentBranch)));
            //读取currentBranch首元节点Commit
       //     String currentTree = FileRead.readTreeFromCommit(new File(wrapObjects(currentCommit)));
            //读取当前Tree
       //     FileCopy.copy(new File(wrapObjects(currentTree)), this.index);
            //删除原HEAD，建立新HEAD
            FileDeletion.deleteFile(HEAD);
            new Head(branchName).writeObject();
        //     Head newHead = new Head(branchName);
        //    new reset().resetHard();
            //更新工作目录
        }else {
            System.out.println("this branch not exists");
        }

    }

    //根据当前分支，创建一个新的名为<branchname>的分支，
    //并切换到此分支上。如果原来就存在该分支，则将其重置。
    public void checkout_b(String branchName) throws Exception{
        if(FileStatus.branchExist(branchName)){
            System.out.println("this barnch has been initiated");
        }
        new Branch(branchName,"").writeObject();
        //   FileCopy.copy(new File(wrapGit(FileRead.readBranchFromHead(this.head))),new File(wrapGit("refs/heads/" + branchName)));
        //新分支指向当前分支所指的Commit
    }

    //两分支的共同祖先Commit
    public String commonAncestor(File branch1, File branch2){
        String commit1 = FileRead.readCommitFromBranch(branch1);
        //两分支的首元节点
        String commit2 = FileRead.readCommitFromBranch(branch2);
        //向后回溯,直到Commit1和Commit2父节点相同
        while(!commit1.equals(commit2)){
            commit1 = FileRead.readParentFromCommit(new File(wrapObjects(commit1)));
            commit2 = FileRead.readParentFromCommit(new File(wrapObjects(commit2)));
        }
        return commit1;
    }
 /*   public static void main(String[] args){
        try{
            new checkout().checkout(args[0]);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }*/
}
